package com.automapper.sqlbuilder.impl;

import java.util.List;
import java.util.Map;

import org.apache.commons.collections4.CollectionUtils;

import com.automapper.constants.ParameterConstants;
import com.automapper.exception.AutoMapperException;
import com.automapper.sqlbuilder.SqlBuilderTemplate;
import com.automapper.utils.PropertiesFacade;

public class InsertRouterSqlBuilder extends SqlBuilderTemplate {	
		
	@Override
	public String buildSql(Object parameterObject, PropertiesFacade propertiesFacade) throws Exception {   
		AutoMapperException.NullRuntimeException(parameterObject, "Sorry,I refuse to build sql for a null object!");
		Map<String, Object> parameterMap = (Map<String, Object>) parameterObject;
		Object paramObj = parameterMap.get(ParameterConstants.PARAM);
		if (isIncludeMapObj(paramObj)) {
			return new InsertMapSqlBuilder().buildSql(parameterObject, propertiesFacade);
		} else {
			return new InsertSqlBuilder().buildSql(parameterObject, propertiesFacade);
		}
	} 
	
	/**
	 * 判断对象是否Map类型或List对象的泛型是否Map类型
	 * @param paramObj
	 * @return 包含Map类型返回true，否则返回false
	 */
	private boolean isIncludeMapObj(Object paramObj) {
		if (paramObj instanceof Map) {
			return true;
		} else if (paramObj instanceof List) {
			if (CollectionUtils.isEmpty((List)paramObj)) {
				return false;
			}
			return ((List)paramObj).get(0) instanceof Map;
		} else {
			return false;
		}
	}
}
